﻿using System;
using System.IO;
using System.Net;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Controls;
using Ama.BugTracker.Models;
using Newtonsoft.Json;

namespace Ama.BugTracker.View.Login
{
    public partial class LoginForm : StackPanel
    {
        private delegate void InvokeDelegate(string param);

        public LoginForm()
        {
            InitializeComponent();

            if (AppUtils.UserConfig.Contains("UserName"))
                this.DataContext = new LoginInfo(AppUtils.UserConfig["UserName"].ToString(), string.Empty);

            this.DataContext = new LoginInfo("请输入用户名", string.Empty);
            this.UserName.GotFocus += new RoutedEventHandler(DoTextBoxGotFocus);
        }

        private void DoTextBoxGotFocus(object sender, RoutedEventArgs e)
        {
            TextBox tb = sender as TextBox;
            if (tb != null)
                tb.Text = string.Empty;
        }

        private void DoUserLogin(object sender, RoutedEventArgs e)
        {
            if (!ValidationSummary.HasErrors)
            {
                string queryString = "name=" + UserName.Text + "&password=" + Password.Password;
                Uri uri = AppUtils.CreateHandlerAddress("/Handler/AuthenticationHandler.ashx", queryString);
                WebRequest request = WebRequest.Create(uri);
                request.Method = "POST";
                request.BeginGetRequestStream(new AsyncCallback(RequestReady), request);
                //AppUtils.ShowContentLoader();
            }
        }

        private void RequestReady(IAsyncResult result)
        {
            WebRequest request = result.AsyncState as WebRequest;
            using (StreamWriter writer = new StreamWriter(request.EndGetRequestStream(result)))
            {
                writer.Write("Post data to server.");
            }
            request.BeginGetResponse(new AsyncCallback(ResponseReady), request);
        }

        private void ResponseReady(IAsyncResult result)
        {
            WebRequest request = result.AsyncState as WebRequest;
            using (WebResponse response = request.EndGetResponse(result))
            {
                using (Stream stream = response.GetResponseStream())
                {
                    using (StreamReader reader = new StreamReader(stream))
                    {
                        Dispatcher.BeginInvoke((InvokeDelegate)BindAndNext, reader.ReadToEnd());
                    }
                }
            }
        }

        private void BindAndNext(string result)
        {
            if (!string.IsNullOrEmpty(result))
            {
                JsonSerializer json = new JsonSerializer();
                StringReader sr = new StringReader(result);
                JsonTextReader reader = new JsonTextReader(sr);

                Dictionary<string, object> data = json.Deserialize<Dictionary<string, object>>(reader);
                sr.Close();
                reader.Close();

                CurrentUser.Id = ulong.Parse(data["id"].ToString());
                CurrentUser.Name = data["name"].ToString();
                CurrentUser.IsSysAdmin = Convert.ToBoolean(data["issysadmin"]);
                CurrentUser.IsTeamAdmin = Convert.ToBoolean(data["isteamadmin"]);

                UserControl control = AppUtils.FindParent<UserControl>(this);
                if (control != null)
                {
                    control.Content = null;
                    control.Content = new MainPage();
                }
            }
            else
            {
                Gmantis.Controls.MessageBox.Show("用户名或密码错误！", "登录异常", Gmantis.Controls.MessageBoxButton.OK, Gmantis.Controls.MessageBoxIcon.Error);
            }
        }
    }
}
